package com.zhbr.mvp.base.view;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zhbr.mvp.base.presenter.BasePresenter;
import com.zhbr.mvp.base.view.IView;

import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements IView {
    protected P mPresenter;
    private Unbinder unbinder;
    protected Context mContent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        mContent=this;
        unbinder = ButterKnife.bind(this);
        // 初始化Presenter
        initPresenter();
        initView();
        initData();
    }

    private void initPresenter() {
        mPresenter = createPresenter();
        // 完成Presenter和view的绑定
        if (mPresenter != null) {
            mPresenter.attachView(this);
        }
    }

    /**
     * 创建Presenter
     *
     * @return Presenter
     */
    protected abstract P createPresenter();

    /**
     * 获取当前activity的id
     *
     * @return 当前xml的布局res ID
     */
    protected abstract int getLayoutId();

    /**
     * 初始化view控件
     */
    protected abstract void initView();
    /**
     * 页面初始化数据
     */
    protected abstract void initData();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 将Presenter和view解绑
        if (mPresenter != null) {
            mPresenter.detachView();
            mPresenter = null;
        }
        // 解绑ButterKnife
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void showLoading() {
        // 这里实现自己的加载弹框
        Toast toast=Toast.makeText(this,"showLoading",Toast.LENGTH_SHORT    );
        toast.show();
    }

    @Override
    public void dismissLoading() {
        // 取消弹框
        Toast toast=Toast.makeText(this,"dismissLoading",Toast.LENGTH_SHORT    );
        toast.show();
    }

    @Override
    public void onFail(Throwable ex, String code, String msg) {
        // 基础的网络请求失败处理
        Log.d("网络请求", "onFail: 请求失败！");
    }

    @Override
    public void onNetError() {
        // 网络错误处理
        Log.d("网络请求", "onNetError: 网络异常！");
        showToast("网络异常！");

    }



    public void showToast(String msg){
        Toast.makeText(mContent,msg,Toast.LENGTH_SHORT).show();
    }
    /**
     * 异步显示
     * @param msg
     */
    public void showToastSync(String msg){
        Looper.prepare();
        Toast.makeText(mContent,msg,Toast.LENGTH_SHORT).show();
        Looper.loop();
    }

    public void navigateTo(Class clazz){
        Intent intent = new Intent(mContent,clazz);
        startActivity(intent);
    }
}